<template>
	<a-row>
		<a-row  class='mb28  mt28  pb10'>
			<a-col  :sm='{offset:3,span:10}'>
				<a-steps  >
				    <a-step  v-for='(item,index) in titleData'  :key='index'>
				      <!-- <span slot="title">{{item.title}}</span> -->
				      <template slot="title">
				        {{item.title}}
				      </template>
				      <span slot="description">{{item.description}}</span>
				    </a-step>
				    <!-- <a-step title="货物信息" description="This is a description." />
				    <a-step title="Waiting" description="This is a description." /> -->
				</a-steps> 
			</a-col>
		</a-row>
		<a-form :layout="formLayout"  :form="form"  @submit="handleSubmit">
			<a-row>
				<a-col  :lg='16' :sm='24'  :xl='12'>
					<a-form-item  style='display: none;'> 
						 <a-input    v-decorator="[ 'prjCode', baseform.prjCode ]" />
					</a-form-item>
					<a-form-item  style='display: none;'> 
						 <a-checkbox-group    v-decorator="[ 'transactionList', baseform.transactionList ]" >
						 </a-checkbox-group>
					</a-form-item>
					<a-form-item
							label="供应商公司"
							:label-col="formItemLayout.labelCol"
							:wrapper-col="formItemLayout.wrapperCol"
						> 
							{{baseInfo.supName}} 
					</a-form-item> 
						<a-form-item  class='mb0'
					          v-for="(k, index) in form.getFieldValue('keys')"
					          :key="k"
					          v-bind="index === 0 ? formItemLayout : formItemLayoutWithOutLabel"
					          :label="index === 0 ? '贸易商' : ''"
					        >
					         <!-- :label-col="{ xs:{ span :24},md:{span:5},lg:{ span: 7 } }"   -->
								<!-- :wrapper-col="{sm:{ span : 16 },xs:{ span :24}} " -->
					        <a-row  class='relative'>
					          	<!-- <a-col  :span='12'> -->
					                 <a-select   @change='(val)=>changeTrade(val,k)'  v-decorator="[ `trade[${k}]`,
							          { validateTrigger: ['change', 'blur'],
							            rules: [ { required: true,message:'请选择'}],
							          }]" >
								      <a-select-option  v-for='(item,index) in tradeOption' :key='index' :value='item.code'  :disabled='item.checked'>{{item.name}}</a-select-option> 
								    </a-select>
					            <!-- </a-col>
					            <a-col  :span='12'>
					            &nbsp;&nbsp;负责人：
					                <a-input  style='display: inline-block;width: 50%' v-decorator="[
					                    `names[${k}].phone`, 
					                  ]"   /> 
					            </a-col>  -->
					             
					            <a-col  :sm='{span:2,offset:1}'  style='position: absolute;top:-24px;right:-20px;'   v-if='index!=0'>
					                <a-button  shape="circle" icon="delete"  type='danger'  class='ml10 mt28'  @click='() => removeActiveItem(k)'></a-button>
					            </a-col>
					        </a-row>  
					    </a-form-item>
					    <a-form-item
					          v-bind='formItemLayoutWithOutLabel'
					    >
					            <a-button type="dashed"  class='cursor  mt12'  block  @click='addActiveItem()' ><a-icon type="plus-circle" />添加</a-button>
					    </a-form-item>
					 
					<a-form-item
							label="买家公司"
							:label-col="formItemLayout.labelCol"
							:wrapper-col="formItemLayout.wrapperCol"  
						>	
							{{baseInfo.buyerName}}
							<!-- <a-input style='display: none;' v-decorator="['buyerCode', baseform.buyerCode]" />  -->
							<!-- <loadSelect  :data_sup='data_sup'   :selected='selectedBuy'
										 :data_sup_total='data_sup_total'
										 :fetching='fetchingBuy' 
										 v-on:search='(val)=>searchBuyer(val)'  
										 v-on:scroll='scrollBuyer'   
										 v-on:valueChange='(val)=>this.baseform.buyerCode.initialValue=val  '></loadSelect> -->
					</a-form-item>
				</a-col>
			</a-row>
			<a-divider></a-divider>
			<a-row>
				<a-col  :xs='{span:24}'  :md='{span:12}'>
					<a-form-item 
							:label-col="formItemLayout.labelCol"
							:wrapper-col="formItemLayout.wrapperCol"
					>
						<span slot="label"  style="position: relative;">
					        出口商 <sup  class='labelsup'>(shipper/exporter)</sup>
					      </span>
						<a-textarea rowspan='5' autosize  v-decorator="['exporter']"  />
					</a-form-item>
					<a-form-item 
							:label-col="formItemLayout.labelCol"
							:wrapper-col="formItemLayout.wrapperCol"
					>
						<span slot="label"  style="position: relative;">
					        出口国 <sup   class='labelsup'>(country of export)</sup>
					      </span>
						<a-input placeholder=""  v-decorator="['countryOfExport']" /> 
					</a-form-item>
					<a-form-item 
							:label-col="formItemLayout.labelCol"
							:wrapper-col="formItemLayout.wrapperCol"
					>
						<span slot="label"  style="position: relative;">
					        货物原产地 <sup  class='labelsup'>(country of origin goods)</sup>
					      </span>
						<a-input placeholder=""  v-decorator="['origin']" /> 
					</a-form-item>
					<a-form-item 
							:label-col="formItemLayout.labelCol"
							:wrapper-col="formItemLayout.wrapperCol"
					>
						<span slot="label"  style="position: relative;">
					        最终抵运目的国 <sup  class='labelsup'>(country of ultimate destination)</sup>
					      </span>
						<a-input placeholder=""  v-decorator="['destination']" /> 
					</a-form-item>
					<a-form-item 
							:label-col="formItemLayout.labelCol"
							:wrapper-col="formItemLayout.wrapperCol"
					>
						<span slot="label"  style="position: relative;">
					        贸易条款 <sup  class='labelsup'>(trade terms)</sup>
					      </span>
						<a-radio-group @change="" v-decorator="['tradeTerms']" >
						    <a-radio  value="1">CIF</a-radio>
						    <a-radio  value="2">FOB</a-radio>
						    <a-radio  value="3">DAP</a-radio>
						    <!-- <a-radio  value="4">
						      More...
						      <a-input v-if="tradeTerms === 4" style="width: 100px" />
						    </a-radio> -->
						  </a-radio-group>
					</a-form-item>
				</a-col>
				<a-col  :xs='{span:24}'  :md='{span:12}'>
					<a-form-item 
							:label-col="formItemLayout.labelCol"
							:wrapper-col="formItemLayout.wrapperCol"
					>
						<span slot="label"  style="position: relative;">
					        收件方 <sup class='labelsup'>(consignee)</sup>
					      </span>
						<a-textarea rowspan='5' autosize   v-decorator="['consignee']"/>
					</a-form-item>
					<a-form-item 
							:label-col="formItemLayout.labelCol"
							:wrapper-col="formItemLayout.wrapperCol"
					>
						<span slot="label"  style="position: relative;">
					        进口商 <sup  class='labelsup'>(importer if other than consignee)</sup>
					      </span>
						<a-textarea rowspan='5' autosize   v-decorator="['importer']"/>
					</a-form-item>
					
				</a-col>
			</a-row>
		     
			
		      <a-form-item

		        :wrapper-col="buttonItemLayout.wrapperCol"
		      >
		      	<router-link to='/order'> <a-button  class='mr20'> 取消 </a-button></router-link>
		        <a-button type="primary"  html-type="submit"  class='mr20' >
		          保存
		        </a-button> 
		        
		      </a-form-item>
    	</a-form>

    	<a-modal title="提示" v-model="visible" @ok="handleOk"  @cancel='handleCancel'>
	      <p>{{currentTip}}</p>
	    </a-modal>
	</a-row>
	 
</template>

<script>
import  loadSelect  from  '@/components/common/loadSelect'

import { customerList }  from  '@/api/customer/index'
import { submitOrder }  from  '@/api/order/index'


export default {
  name: 'orderAdd',
  data () { 
    return {
    	/*form  布局*/
      	formLayout:'horizontal',
      	formItemLayout:{
      		labelCol: {xs:{ span :24},md:{span:5},lg:{ span: 7 }},  //label 标签布局
        	wrapperCol: {xxl:{ span: 8 },xl:{ span : 11},lg:{ span :14 },md:{ span : 16 },xs:{ span :24}}, 
      	},
      	tradeOption:[],/*代理方option*/
      	titleData:[
      		{title:'交易主体及要素录入',description:''},
      		{title:'订单货物信息录入',description:''},
      	],
      	value:1,
      	 formItemLayoutWithOutLabel: {   //新增联系人label
          wrapperCol: {
            xs: { span: 24, offset: 0 },
            md: { span: 16, offset: 5 },
            lg: { span: 14, offset: 7 },
            xl: { span: 11, offset: 7 },
            xxl: { span: 8, offset: 7 },
          },
        },
      	id:0,

      	/*form-rule*/
	    baseform:{
      		prjCode: {initialValue:''}, 
      		transactionList:{initialValue:[]},
      	},
      	//基本信息form
      	baseInfo:{
      		supName:'',
      	},

      	/*data 买方公司*/
		data_sup: [],
		data_sup_total:null,
		/*data loading */
		requestInit_buy:false,
		fetchingBuy: false,
		searchBuy:{
			keyWord:'',
			supOrBuyer:2,
			pageNo:1,
			pageSize:10
		}, 

		data_Supply: [],
		data_sup_totalSupply:null,
		requestInit_supply:false,
		fetchingSupply:false,
		search_Supply:{
			keyWord:'',
			supOrBuyer:1,
			pageNo:1,
			pageSize:10
		}, 

		selectedBuy:'',
		selectedSupply:'',

      	uploadAddress:process.env.BASE_API+'/op/fileupload/upload_file',
      	/*上传文件  request-header*/   
		headers: {
		//authorization: 'authorization-text',
		},  

      	//modal框
      	visible:false,
      	currentTip:'',            

      	/*动态select id设置*/
      	tradeId:1,                                                
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this); 
    /*动态生成表单选项*/
    this.form.getFieldDecorator('keys', { initialValue: [0,1], preserve: true });
  },
  created(){ 
  	this.baseInfo = this.$route.query.record
  	// this.baseInfo.supName = this.$route.query.supName
  	this.baseform.prjCode.initialValue = this.baseInfo.code
  	this.pageInit()
  },
  mounted(){
  	
  },
  methods:{
  	pageInit(){ 
  		let CompanyFun = new Promise((resolve,reject)=>{ 
		 	customerList({pageSize:100,supOrBuyer:4}).then((res)=>{
		 		if(res.data.flag == true){
		 			resolve(res.data.dataList)
		 		}
		 		else{
		 			reject()
		 		}
		 	}) 
		})
		 
		Promise.all([CompanyFun]).then(([result])=>{
			this.tradeOption = result
		}).catch((error)=>{

		})
  	},
  	changeTrade(val,k){
  		//old_value
  		let old_value = this.form.getFieldValue('trade')[k]  
  		 
		this.tradeOption.forEach((item,index)=>{ 
			//new_value
			if(item.code == val){
				item.checked = true
			}
			if(old_value!=undefined){
				if(item.code==old_value){
					item.checked = false
				}
			}
		}) 
  		// console.log(this.form.getFieldValue('trade')[k])  
  	},
  	/*买方公司  input-change*/
	    searchBuyer(val){
	    	let value = val
	    	/**不用特设值等于多少，值变化时设置*/
	    	if(value != this.searchBuy.keyWord){
	    		this.requestInit_buy = true
	    		this.searchBuy.pageNo = 1
	    		this.data_sup  =[]
	    	}
	    	/*设定搜索值*/
	        this.searchBuy.keyWord = value
	        /*loading*/
	        this.fetchingBuy = this.requestInit_buy == true? true : false;//因为这个占用v-if  导致数据重新渲染，所以会一直跳到scrollTop为0

	        customerList(this.searchBuy)
	          .then(body => {
	          	this.data_sup_total = body.data.totalRs
	          	if(this.data_sup.length<this.data_sup_total){
			          	body.data.dataList.forEach((item)=>{
			          		this.data_sup.push({code:item.code,name:item.name})
			          	})
	          	}
	            this.fetchingBuy =  false;
	          });
	    },
	    /*买方公司  value-change*/
	    scrollBuyer(){
	    	this.searchBuy.pageNo +=1
		    this.requestInit_buy = false
		    this.searchBuyer(this.searchBuy.keyWord)
	    },
	    change(val){
	    	console.log(val)
	    },
  	 /*供应商公司  input-change*/
	    searchSupply(value){
	    	// let value = val
	    	/**不用特设值等于多少，值变化时设置*/
	    	if(value != this.search_Supply.keyWord){
	    		this.requestInit_supply = true
	    		this.search_Supply.pageNo = 1
	    		this.data_Supply  =[]
	    	}
	    	/*设定搜索值*/
	        this.search_Supply.keyWord = value
	        /*loading*/
	        this.fetchingSupply = this.requestInit_supply== true? true : false;//因为这个占用v-if  导致数据重新渲染，所以会一直跳到scrollTop为0

	        customerList(this.search_Supply)
	          .then(body => {
	          	this.data_sup_totalSupply = body.data.totalRs
	          	if(this.data_Supply.length<this.data_sup_totalSupply){
			          	body.data.dataList.forEach((item)=>{
			          		this.data_Supply.push({code:item.code,name:item.name})
			          	})
	          	}
	            this.fetchingSupply =  false;
	          });
	    },
	    /*供应商公司  value-change*/
	    scrollSupply(){
	    	this.search_Supply.pageNo +=1
		    this.requestInit_supply = false
		    this.searchSupply(this.search_Supply.keyWord)
	    },

	/*动态表单增删*/
	/*添加*/
    addActiveItem(){
      const { form } = this;
      // can use data-binding to get
      const keys = form.getFieldValue('keys');
      const nextKeys = keys.concat(++this.tradeId);
      // can use data-binding to set
      // important! notify form to detect changes
      form.setFieldsValue({
        keys: nextKeys,
      });

    },
    /*移除*/
    removeActiveItem  (k) {
      const { form } = this;
      // can use data-binding to get
      const keys = form.getFieldValue('keys');
      // We need at least one passenger
      if (keys.length === 1) {
      	return;
      } 
      let old_value = this.form.getFieldValue('trade')[k]   
		this.tradeOption.forEach((item,index)=>{  
			if(item.code==old_value){
				item.checked = false
			} 
		})
      // can use data-binding to set
      form.setFieldsValue({
      		keys: keys.filter(key => key !== k),
      });
      	
    },
     
    handleOk(){ 
    	this.$router.push("{path:'/order/cargoadd',query:{code:record.code}}")
    },
    handleCancel(){ 
    	this.$router.push('/order')
    },
  	beforeUpload(file,fileList){
  		console.log(file,fileList)
  	},
  	/*提交表单*/
	handleSubmit (e) {
		e.preventDefault();
		// console.log(this.form.getFieldsValue())
		this.form.validateFields((err, values) => {
			if (!err) { 
			  // console.log('Received values of form: ', values); 
			  // 供应商-买方 传递
			  let supplierCode = this.baseInfo.supplierCode
			  let buyerCode =this.baseInfo.buyerCode

			  // 交易关系动态
			  let keys = this.form.getFieldValue('keys'); //[0,2]
			  let trade = this.form.getFieldValue('trade'); //['12',empty,'34']
			  let keys_length = keys.length-1
			  
			  values.transactionList.push({buyer:supplierCode,seller:trade[0],transactionType:1}) 
			  keys.forEach((item,index)=>{  
			  	if(index<keys_length){ 
			  		values.transactionList.push({buyer:trade[item],seller:trade[keys[index+1]],transactionType:2})
			  	} 
			  })  
			  values.transactionList.push({buyer:trade[keys[keys_length]],seller: buyerCode,transactionType:3}) 
			   // console.log('Received values of form: ', values); 
			   delete values.trade
			  submitOrder(values).then((res)=>{
			  		if(res.data.flag == true){
			  			this.$message.success(res.data.msg)
			  			this.$router.push('/order')
			  			// this.currentTip=res.data.msg+'，是否进入下一步填写货物信息？'
    				// 	this.visible = true
			  		}
			  })
			}
			else{
				console.log(err)
			}
		});
	},
		
	     
  },
	computed: {
		
		buttonItemLayout () {
			const { formLayout } = this;
			return formLayout === 'horizontal' ? {
			wrapperCol: { span: 14, offset: 7 },
			} : {};
		},
		
	},
  components: {
  	loadSelect
    
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
/*.ant-input{width: 200px;}*/
.labelsup{right:-6px;position: absolute;top:22px}
</style>
